package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.AddressBook;
import com.sky.entity.OrderDetail;
import com.sky.entity.Orders;
import com.sky.entity.ShoppingCart;
import com.sky.exception.InvalidParamException;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.AddressBookMapper;
import com.sky.mapper.OrderDetailMapper;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.ShoppingCartMapper;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.OrderService;
import com.sky.utils.BaiduMapUtil;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.webSocket.WebSocketServer;
import io.swagger.util.Json;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PutMapping;

import java.time.LocalDateTime;
import java.util.*;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private BaiduMapUtil baiduMapUtil;

    @Autowired
    private WebSocketServer webSocketServer;


    /**
     * 提交订单
     * @param dto
     * @return
     */
    @Transactional
    @Override
    public Result<OrderSubmitVO> submit(OrdersSubmitDTO dto) throws Exception {

        //1.判断非法参数（地址ID、订单金额、预计配送时间、打包费、支付方式）
        if(dto.getAddressBookId()==null
                || dto.getAmount()==null
                || dto.getEstimatedDeliveryTime()==null
                || dto.getPackAmount() == null
                || dto.getPayMethod()==0
        ) {
            throw new InvalidParamException("非法参数");
        }
        //健壮性判断
        Long currentId = BaseContext.getCurrentId();
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(currentId);
        List<ShoppingCart> list = shoppingCartMapper.list(shoppingCart);
        //购物车没有订单 报异常
        if (CollectionUtils.isEmpty(list)){
            throw new OrderBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        //获取地址信息
        AddressBook addressBook = addressBookMapper.getById(dto.getAddressBookId());
        //地址不存在 报异常
        if (addressBook==null){
            throw new OrderBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }


     //0.距离大于5公里下单失败

//        int mileage = baiduMapUtil.getMileage(addressBook.getProvinceName()+addressBook.getCityName()+addressBook.getDistrictName()+addressBook.getDetail());
//        if (mileage>5000){
//            throw new OrderBusinessException(mileage+"米，太远了送不了");
//        }



        //拷贝数据
        Orders orders = new Orders();
        BeanUtils.copyProperties(dto,orders);
        //补全数据
        orders.setPhone(addressBook.getPhone());
        orders.setAddress(addressBook.getProvinceName()+addressBook.getCityName()+addressBook.getDistrictName()+addressBook.getDetail());
        orders.setUserName(addressBook.getConsignee());
        orders.setUserId(addressBook.getUserId());
        orders.setConsignee(addressBook.getConsignee());
        orders.setStatus(Orders.PENDING_PAYMENT);//订单状态
        orders.setPayStatus(Orders.UN_PAID);//支付状态
        orders.setOrderTime(LocalDateTime.now());//下单时间
        orders.setNumber(String.valueOf(System.currentTimeMillis()));//订单号
        //新增订单数据
        orderMapper.insert(orders);

        //新增订单详情
        //构建订单数据
        List<OrderDetail> orderDetailList = new ArrayList<>();

        for (ShoppingCart cart : list) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart,orderDetail);
            orderDetail.setOrderId(orders.getId());
            orderDetailMapper.insert(orderDetail);
            orderDetailList.add(orderDetail);
        }


        //清空购物车
        shoppingCartMapper.delteBySetmalOrDishId(shoppingCart);

        //封装返回数据
        OrderSubmitVO vo = new OrderSubmitVO();

        vo.setId(orders.getId());
        vo.setOrderNumber(orders.getNumber());
        vo.setOrderAmount(orders.getAmount());
        vo.setOrderTime(orders.getOrderTime());

        return Result.success(vo);
    }

    /**
     * 历史订单
     * @param dto
     * @return
     */
    @Override
    public Result<PageResult> historyOrders(OrdersPageQueryDTO dto) {
        //开启分页，设置参数
        PageHelper.startPage(dto.getPage(),dto.getPageSize());
        Long userId = BaseContext.getCurrentId();
        //查询登录人的历史订单
        Page<OrderVO> ordersList = orderMapper.historyOrders(userId,dto);
        //查询每个订单的详情
        for (OrderVO orderVo : ordersList) {
            List<OrderDetail> detail = orderDetailMapper.historyOrdersByOrderId(orderVo.getId());
            orderVo.setOrderDetailList(detail);
        }

        //封装返回数据
        PageResult pageResult = new PageResult();
        pageResult.setRecords(ordersList);
        pageResult.setTotal(ordersList.getTotal());
        return Result.success(pageResult) ;
    }

    /**
     * 查看订单详情
     * @param id
     * @return
     */
    @Override
    public Result<OrderVO> orderDetail(Long id) {
        //查询订单数据
        OrderVO orderVO = orderMapper.historyOrdersByOrderId(id);
        //查询订单详情数据
        List<OrderDetail> orderDetailList = orderDetailMapper.historyOrdersByOrderId(orderVO.getId());
        //封装数据
        orderVO.setOrderDetailList(orderDetailList);

        return Result.success(orderVO);
    }

    /**
     * 取消订单
     * @param id
     * @return
     */
    @Override
    public Result cancel(Long id) {
        orderMapper.cancel(id);
        return Result.success();
    }

    /**
     * 再来一单
     * @param id
     * @return
     */
    @Override
    public Result repetition(Long id) {//订单id
        //根据订单id查询订单信息以及订单详情
        //查询订单详情
        List<OrderDetail> orderDetailList = orderDetailMapper.historyOrdersByOrderId(id);
        for (OrderDetail orderDetail : orderDetailList) {
            ShoppingCart shoppingCart = new ShoppingCart();
            shoppingCart.setUserId(BaseContext.getCurrentId());
            shoppingCart.setAmount(orderDetail.getAmount());
            shoppingCart.setNumber(orderDetail.getNumber());
            shoppingCart.setImage(orderDetail.getImage());
            shoppingCart.setName(orderDetail.getName());
            shoppingCart.setSetmealId(orderDetail.getSetmealId());
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCart.setDishFlavor(orderDetail.getDishFlavor());
            shoppingCartMapper.insert(shoppingCart);
        }
        return Result.success();
    }

    /**
     * 管理端历史订单查询
     * @param dto
     * @return
     */
    @Override
    public Result<PageResult> conditionSearch(OrdersPageQueryDTO dto) {
        //1.开启分页，设置参数
        PageHelper.startPage(dto.getPage(),dto.getPageSize());

        //2.查询当前用户的订单数据
//        Long userId = BaseContext.getCurrentId();
        Page<OrderVO> orderVOList = orderMapper.historyOrders(null,dto);

        //3.封装返回数据
        PageResult pageResult = new PageResult();
        pageResult.setTotal(orderVOList.getTotal());
        pageResult.setRecords(orderVOList);
        return Result.success(pageResult);
    }

    /**
     * 各个订单数量的查询
     * @return
     */
    @Override
    public Result<OrderStatisticsVO> statistics() {
//        List<Map<String,String>> list = orderMapper.statistics();

        Integer toBeConfirmed = orderMapper.statistics(Orders.TO_BE_CONFIRMED);
        Integer confirmed = orderMapper.statistics(Orders.CONFIRMED);
        Integer deliveryInProgress = orderMapper.statistics(Orders.DELIVERY_IN_PROGRESS);
        OrderStatisticsVO vo = new OrderStatisticsVO();
        vo.setConfirmed(confirmed);
        vo.setToBeConfirmed(toBeConfirmed);
        vo.setDeliveryInProgress(deliveryInProgress);
        return Result.success(vo);
    }

    /**
     * 查看订单详情
     * @param id
     * @return
     */
    @Override
    public Result<OrderVO> details(Long id) {
        //查询详情
        OrderVO orderVO = orderMapper.historyOrdersByOrderId(id);
        List<OrderDetail> orderDetailList = orderDetailMapper.historyOrdersByOrderId(id);
        orderVO.setOrderDetailList(orderDetailList);
        return Result.success(orderVO);
    }

    /**
     * 接单
     * @param dto 存放订单id
     * @return
     */
    @Override
    public Result updateStatus(OrdersConfirmDTO dto) {
        //1.status=2才可以接单
        OrderVO orderVO = orderMapper.historyOrdersByOrderId(dto.getId());
        if (orderVO.getStatus()!=2) {
            throw new OrderBusinessException("订单状态有误~");
        }
        Orders order = Orders.builder()
                .status(Orders.CONFIRMED)
                .id(dto.getId())
                .build();
        orderMapper.updateStatus(order);
        return Result.success();
    }

    /**
     * 派单
     * @param id
     * @return
     */
    @Override
    public Result delivery(Long id) {
        //1.status=3才可以派单
        OrderVO orderVO = orderMapper.historyOrdersByOrderId(id);
        if (orderVO.getStatus()!=3) {
            throw new OrderBusinessException("订单状态有误~");
        }
        Orders order = Orders.builder()
                .status(Orders.DELIVERY_IN_PROGRESS)
                .id(id)
                .build();
        orderMapper.updateStatus(order);
        return Result.success();
    }

    /**
     * 取消订单
     * @param dto
     * @return
     */
    @PutMapping("/cancel")
    public Result cancel (OrdersCancelDTO dto){

        //1.状态小于6才可以取消
        OrderVO orderVO = orderMapper.historyOrdersByOrderId(dto.getId());
        if (orderVO.getStatus()>5) {
            throw new OrderBusinessException("订单状态有误~");
        }
        Orders order = Orders.builder()
                .status(Orders.CANCELLED)
                .id(dto.getId())
                .cancelReason(dto.getCancelReason())
                .build();
        orderMapper.updateStatus(order);
        return Result.success();
    }

    /**
     * 拒单
     * @param dto
     * @return
     */
    @PutMapping("/cancel")
    public Result rejection (OrdersRejectionDTO dto){

        //TODO 1.调用微信接口退款

        Orders order = Orders.builder()
                .status(7)
                .id(dto.getId())
                .rejectionReason(dto.getRejectionReason())
                .build();
        orderMapper.updateStatus(order);
        return Result.success();
    }

    /**
     * 完成订单
     * @param id
     * @return
     */
    @Override
    public Result complete(Long id) {

        Orders order = Orders.builder()
                .status(Orders.COMPLETED)
                .id(id)
                .build();
        orderMapper.updateStatus(order);
        return Result.success();
    }

    /**
     * 用户催单
     * @return
     */
    @Override
    public Result reminder(Long id) {
        OrderVO orderVO = orderMapper.historyOrdersByOrderId(id);
        if (orderVO==null){
            throw new OrderBusinessException("订单不存在");
        }
        //基于WebSocket实现催单
        Map map = new HashMap();
        map.put("type",2);//2代表用户催单
        map.put("orderId", id);
        map.put("content", "订单号：" + orderVO.getNumber());
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
        System.out.println(JSON.toJSONString(map));
        return Result.success();
    }
}
